package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.base.response.JsonResult;
import cn.tedu.coolshark.mapper.BannerMapper;
import cn.tedu.coolshark.pojo.entity.Banner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/banner")
@Api(tags="轮播图模块管理")
public class BannerController {
    @Autowired
    private BannerMapper bannerMapper;
    @Value("${imagesPath}")
    private String dirPath;

    @GetMapping("/select")
    @ApiOperation(value = "查询所有轮播图",notes = "返回Banner实体类的List集合")
    public List<Banner> created() {
        return bannerMapper.selectAll();
    }

    @GetMapping("/selectById")
    @ApiOperation(value = "根据id查询轮播图")
    @ApiImplicitParam(name = "id", value = "轮播图id", required = true)
    public Banner selectById(Integer id) {
        return bannerMapper.selectById(id);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "根据id删除轮播图",notes = "同时删除服务器端的图片资源")
    @ApiImplicitParam(name = "id", value = "轮播图id", required = true)
    public int delete(Integer id) {
        Banner banner = bannerMapper.selectById(id);
        File targetFile = new File(dirPath + banner.getUrl());
        if (targetFile.exists()) targetFile.delete();
        return bannerMapper.delete(id);
    }

    @PostMapping("/insert")
    @ApiOperation(value = "插入轮播图")
    @ApiImplicitParam(name = "url", value = "上传得到的轮播图url", required = true)
    public int insert(String url) {
        int id;
        if (bannerMapper.selectMaxId() == null) {
            id = 1;
        } else {
            id = bannerMapper.selectMaxId() + 1;
        }
        String newUrl = "/imgs/b" + id + "." + url.split("\\.")[1];
        ControllerUtils.rename(url, newUrl);
        return bannerMapper.insert(newUrl);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新轮播图")
    @ApiImplicitParam(name = "banner", value = "轮播图对象", required = true)
    public void update(@RequestBody Banner banner) {
        Banner oldBanner = bannerMapper.selectById(banner.getId());
        String oldUrl = oldBanner.getUrl();
        String newUrl = banner.getUrl();
        ControllerUtils.rename(newUrl, oldUrl);
    }

}
